import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
// import 'package:plugin/plugin.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/mqtt.dart';
import 'package:wch/page/data_stage.dart';
import 'package:wch/page/delivery_user.dart';
import 'package:wch/page/doctor_info.dart';
import 'package:wch/page/help.dart';
import 'package:wch/page/wifi_sest.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/business_widget.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../helper/preferences_helper.dart';
import '../utils/loading_utils.dart';
import 'about.dart';
import 'login.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({super.key, required this.id});

  final String id;

  @override
  State<SettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {

  String cacheStr = '0.00b';

  OverlayEntry? entry;

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(title: '设置', body: Container(
      color: Color(0xFFF8F9FB),
      child: Column(
        children: [
          Container(
            height: 52.h*5,
            margin: EdgeInsets.all(15),
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
              color: Colors.white
            ),
            child: ListView.separated(itemBuilder: (ctx, id){
              if (id == 0) {
                return InkWell(onTap: (){
                  NavigatorUtil.push(context, DoctorInfoPage(id: widget.id,));
                }, child: CommonInputWidget.getSetSelectWidget('用户信息', ''));
              } else if (id == 1) {
                return InkWell(onTap: (){
                  NavigatorUtil.push(context, AboutPage());
                }, child: CommonInputWidget.getSetSelectWidget('关于', ''));
              } else if (id == 2) {
                return InkWell(onTap: (){
                  NavigatorUtil.push(context, HelpPage());
                }, child:  CommonInputWidget.getSetSelectWidget('帮助', ''));
              } else if (id == 3) {
                return InkWell(onTap: (){
                  if (cacheStr == '0.00b') {
                    ToastUtils.showToast(msg: '无缓存数据，不需要清除哦~');
                    return;
                  }
                  Loading.getIns().loading(msg: '清理缓存中');
                  Timer.periodic(Duration(milliseconds: 800), (timer) async {
                    timer.cancel();
                    delDir(await getTemporaryDirectory());
                    setState(() {
                      cacheStr = '0.00b';
                    });
                    Loading.getIns().success(msg: '清理成功');
                  });

                }, child: CommonInputWidget.getSetSelectWidget('清理缓存', cacheStr));
              } else if (id == 4) {
                return InkWell(onTap:(){
                  NavigatorUtil.push(context, WifiSetPage());
                //   NavigatorUtil.push(context, DataStagePage());
                },child: CommonInputWidget.getSetSelectWidget('Wi-Fi设置', ''));
              }
            }, separatorBuilder: (ctx, id){
              return Divider(
                color: Color(0xFFE6E6E6),
                height: 0.5,
                thickness: 0.5,
              );
            }, itemCount: 5),
          ),
          Expanded(child: Container()),
          GestureDetector(
            onTap: (){
              entry = OverlayEntry(builder: (ctx){
                return CommonAlert(title: '退出登录', msg: '您确定退出登录吗？', callback: (index){
                  if (index == 1) {
                    NavigatorUtil.closeAllPage(context, const LoginPage());
                    PreferencesHelper.clearToken();
                    disConnectMqtt();
                  }
                }, entry: entry!);
              });
              Overlay.of(context).insert(entry!);
              // entry = OverlayEntry(builder: (ctx){
              //   return AlertInputWidget(callback: (id){
              //
              //   }, title: '配网设置', entry: entry!, btns: ['取消', '确定'], msg: 'Wi-Fi名称：XJ-0c6abe', hint: '请输入密码',);
              // });
            },
            child: Container(
              alignment: Alignment.center,
              height: 50.h,
              width: ScreenUtil().screenWidth - 30.w,
              margin: EdgeInsets.symmetric(horizontal: 15.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(7.5.w)),
                color: Colors.white
              ),
              child: F16TitleText(
                '退出登录',
                color: themeColor,
              ),
            ),
          ),
          VerPadding(90.h),
        ],
      ),
    ));
  }

  @override
  void initState() {
    getSize();

  }

  ///获取缓存大小
  getSize() async {
    final tempDir = await getTemporaryDirectory();
    double cache = await getTotalSizeOfFilesInDir(tempDir);
    setState(() {
      if (cache > 1024 * 1024) {
        cache /= 1024*1024;
        cacheStr = '${cache.toStringAsFixed(2)}M';
      } else if (cache > 1024) {
        cache /= 1024;
        cacheStr = '${cache.toStringAsFixed(2)}K';
      } else {
        cacheStr = '${cache.toStringAsFixed(2)}b';
      }
    });
  }
  ///循环获取缓存大小
  Future getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    //  File
    if (file is File && file.existsSync()) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory && file.existsSync()) {
      List children = file.listSync();
      double total = 0;
      if (children.isNotEmpty)
        for (final FileSystemEntity child in children) {
          total += await getTotalSizeOfFilesInDir(child);
        }
      return total;
    }
    return 0;
  }
  ///删除目录
  Future<void> delDir(FileSystemEntity file) async {
    if (file is Directory && file.existsSync()) {
      LogUtils.log('delPath=${file.path}');
      final List<FileSystemEntity> children =
      file.listSync(recursive: true, followLinks: true);
      for (final FileSystemEntity child in children) {
        await delDir(child);
      }
    }
    try {
      if (file.existsSync()) {
        await file.delete(recursive: true);
      }
    } catch (err) {
      print(err);
    }
  }

}
